package com.hfut.android.plana


import android.app.AlertDialog
import android.app.DatePickerDialog
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import com.hfut.android.plana.ui.plan.AddStuffViewModel
import kotlinx.android.synthetic.main.fragment_fragment_add_stuff.*
import java.text.SimpleDateFormat
import java.util.*


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 *
 */

class FragmentAddStuff : Fragment() {
    private lateinit var viewModel: AddStuffViewModel
    private var frequency = DAILY
    private var img: Int = R.drawable.icon_list

    private var format = SimpleDateFormat("yyyyMMdd")
    private val date = Date(System.currentTimeMillis())
    private val calendar1 = com.haibin.calendarview.Calendar()
    private val calendar2 = com.haibin.calendarview.Calendar()

    private val calendar = Calendar.getInstance()
    private val listener = View.OnClickListener{
        when(it){
            startTime -> {
                datePickerStart()
            }

            endTime -> {
                datePickerEnd()
            }
        }
    }

    private val dateListenerStart = DatePickerDialog.OnDateSetListener { _, year, month, day ->
        calendar.set(year,month,day)
        format("yyyy / MM / dd",add_tv_start_time)
        calendar1.year = year
        calendar1.month = month+1
        calendar1.day = day
    }

    private val dateListenerEnd = DatePickerDialog.OnDateSetListener { _, year, month, day ->
        calendar.set(year,month,day)
        format("yyyy / MM / dd",add_tv_end_time)
        calendar2.year = year
        calendar2.month = month+1
        calendar2.day = day
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_add_stuff, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(AddStuffViewModel::class.java)

        back_main.setOnClickListener {
            findNavController().navigate(R.id.action_add_to_main)
        }

        startTime.setOnClickListener(listener)
        endTime.setOnClickListener(listener)

        gp_frequency.setOnCheckedChangeListener({_, checkedId ->
            val index = when (checkedId) {
                R.id.daily -> 0
                R.id.weekly -> 1
                else -> 2
            }
            if (index == 0) {
                frequency = DAILY
            } else if (index == 1) {
                frequency = WEEKLY
            }

        })

        gp_icon.setOnCheckedChangeListener({_, checkedId ->
            val index = when (checkedId) {
                R.id.study -> 0
                R.id.english -> 1
                R.id.ball -> 2
                R.id.list -> 3
                else -> 4
            }
            if (index == 0) {
                img = R.drawable.icon_study
            } else if (index == 1) {
                img = R.drawable.icon_english
            } else if (index == 2) {
                img = R.drawable.icon_ball
            } else if (index == 3) {
                img = R.drawable.icon_list
            }

        })


        submit.setOnClickListener {
            if (calendar1.timeInMillis > calendar2.timeInMillis
                // (calendar2.timeInMillis-calendar1.timeInMillis)/1000/60/60/24+1 < editText.text.toString().toInt()
                || calendar1.toString().toInt() < format.format(date).toString().toInt()
                || editText.text.toString() == ""
                || calendar1 == null
                || calendar2 == null
            ) {
                Dialog()
            } else {
                val taskNum = (calendar2.timeInMillis-calendar1.timeInMillis)/1000/60/60/24+1
                viewModel.insertPlan(
                    editText.text.toString(),
                    editText.text.toString(),
                    img,
                    calendar1,
                    calendar2,
                    frequency,
                    //editText.text.toString().toInt()
                    taskNum.toInt()
                )
                findNavController().navigate(R.id.actionAddStuffBack)
            }
        }

    }

    fun format(format:String,view:View) {
        val time = SimpleDateFormat(format, Locale.CHINA)
        (view as TextView).setText(time.format(calendar.time))
    }

    fun datePickerStart(){
        DatePickerDialog(context!!,
            R.style.ThemeDialog,
            dateListenerStart,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    fun datePickerEnd(){
        DatePickerDialog(context!!,
            R.style.ThemeDialog,
            dateListenerEnd,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    fun Dialog(){
        AlertDialog.Builder(context!!)
            .setTitle("error")
            .setMessage("输入错误")
            .setNegativeButton("OK"){dialog, _ ->
                dialog.cancel()
            }.create().show()
    }

}
